<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName" />
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select
          placeholder="请选择"
          style="width: 260px"
          v-model="spuParams.tmId"
        >
          <el-option
            :value="item.id"
            v-for="item in tradeMarkList"
            :label="item.tmName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          v-model="spuParams.description"
        />
      </el-form-item>
      <el-form-item label="SPU图标">
        <!--上传组件：
          file-list / v-model:file-list:默认上传文件
          on-preview:点击文件列表中已上传的文件时的钩子
          on-remove	文件列表移除文件时的钩子
        -->
        <el-upload
          v-model:file-list="spuImageList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <el-select
          style="width: 260px"
          v-model="saleIdAndValueName"
          :placeholder="
            unSelectSpuSaleAttr.length
              ? `未选择属性有${unSelectSpuSaleAttr.length}个`
              : '无'
          "
        >
          <el-option
            v-for="item in unSelectSpuSaleAttr"
            :value="`${item.id}:${item.name}`"
            :key="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
        <el-button
          icon="Plus"
          type="primary"
          style="margin-left: 10px"
          :disabled="!saleIdAndValueName"
          @click="addSaleAttr"
          >添加属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table border :data="spuSaleList">
          <el-table-column
            label="序号"
            width="80"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column
            label="销售属性名字"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="销售属性值">
            <template #="{ row }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                style="margin-right: 5px"
                size="small"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-model="row.saleAttrValue"
                v-if="row.flag == true"
                size="small"
                style="width: 60px"
                @blur="toLook(row)"
              ></el-input>
              <el-button
                v-else
                size="small"
                type="primary"
                icon="Plus"
                style="margin: 0 5px"
                @click="toEdit(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                icon="Delete"
                type="danger"
                size="small"
                @click="spuSaleList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="saveSpuData"
          :disabled="spuSaleList.length > 0 ? false : true"
          >保存</el-button
        >
        <el-button type="primary" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
//引入ts类型
import type { SpuData } from "@/api/product/spu/type";
import type { TradeMark } from "@/api/product/trademark/type";
import type {
  SpuImage,
  SaleAttrValue,
  AllSaleAttr,
  SaleValueList,
} from "@/api/product/spu/type";
//引入API
import {
  reqAllTrademark,
  reqSpuImage,
  reqSpuHasSale,
  reqAllSale,
  reqAddOrUpdateSpu,
} from "@/api/product/spu";
import { reactive, ref, computed } from "vue";
import { defineOptions } from "vue";
import { ElMessage } from "element-plus";
defineOptions({
  name: "SpuForm",
});
let emit = defineEmits(["changeScene"]); //自定义事件
let tradeMarkList = ref<TradeMark[]>([]); //存储全部SPU品牌
let spuImageList = ref<SpuImage[]>([]); //存储某个SPU下售卖商品图片
let spuSaleList = ref<SaleAttrValue[]>([]); //存储某一SPU下已有的销售属性
let allSaleList = ref<AllSaleAttr[]>([]); //存储全部销售属性【颜色 版本 尺码】
//spu携带的数据
let spuParams = reactive<SpuData>({
  spuName: "",
  description: "",
  category3Id: "",
  tmId: "",
  spuSaleAttrList: [],
  spuImageList: [],
});
let dialogVisible = ref<boolean>(false); //图片的显示与隐藏
let dialogImageUrl = ref<string>(""); //收集显示图片的地址
let saleIdAndValueName = ref<string>(""); //收集还未选择的销售属性的ID和名字
//点击取消按钮通知父组件更改场景切换
const cancel = () => {
  emit("changeScene", { sceneNum: 0, params: "update" });
};
//获取已有SPU的数据
const initSpuFormData = async (row: SpuData) => {
  //储存已有的SPU对象,将来在模版中展示
  Object.assign(spuParams, row);
  //请求方法
  let resTrademark = await reqAllTrademark();
  let resSpuImage = await reqSpuImage(row.id as string);
  let resSpuSale = await reqSpuHasSale(row.id as string);
  let resAllSale = await reqAllSale();
  //存储全部SPU品牌
  tradeMarkList.value = resTrademark.data;
  //存储某个SPU下售卖商品图片
  spuImageList.value = resSpuImage.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  //存储某一SPU下已有的销售属性
  spuSaleList.value = resSpuSale.data;
  //存储全部销售属性【颜色 版本 尺码】
  allSaleList.value = resAllSale.data;
};
//点击文件列表中已上传的文件时的钩子
const handlePictureCardPreview = (file: any) => {
  // console.log(file);
  //收集图片的地址
  dialogImageUrl.value = file.url;
  //显示图片
  dialogVisible.value = true;
};
//文件移除钩子 uploadFile:移除的对象；uploadFiles:目前还有多少未移除的图片数组
const handleRemove = (uploadFile: any, uploadFiles: any) => {
  console.log(uploadFile, uploadFiles);
};
//计算未选择的SPU下的销售属性
let unSelectSpuSaleAttr = computed(() => {
  let unSelectAttr = allSaleList.value.filter((allSale) => {
    return spuSaleList.value.every((sale) => {
      return sale.saleAttrName != allSale.name;
    });
  });
  return unSelectAttr;
});
//添加销售属性
let addSaleAttr = () => {
  //解构ID和销售名字
  const [baseSaleAttrId, saleAttrName] = saleIdAndValueName.value.split(":");
  //收集新增销售数据 将来带给服务器
  let newSaleAttr: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  //追加到数组中
  spuSaleList.value.push(newSaleAttr);
  //清空数据
  saleIdAndValueName.value = "";
};

//属性值button点击按钮的回调(切换为input模式)
const toEdit = (row: SaleAttrValue) => {
  row.flag = true;
  row.saleAttrValue = "";
};

//属性值input点击按钮的回调(切换为button模式)
const toLook = (row: SaleAttrValue) => {
  const { baseSaleAttrId, saleAttrValue } = row;
  // console.log(baseSaleAttrId,saleAttrValue,typeof saleAttrValue)
  //属性值内容不能为空
  if (saleAttrValue == undefined || saleAttrValue.trim() == "") {
    ElMessage({
      type: "error",
      message: "属性值内容不能为空",
    });
    return;
  }
  //属性值不能重复
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue;
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
    return;
  }
  //收集数据
  let newSaleAttr: SaleValueList = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue,
  };
  //新增数据到spuSaleAttrValueList数组中
  row.spuSaleAttrValueList.push(newSaleAttr);
  //切换为button模式
  row.flag = false;
};

//添加一个SPU
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(spuParams, {
    id: "",
    spuName: "",
    description: "",
    category3Id: "",
    tmId: "",
    spuSaleAttrList: [],
    spuImageList: [],
  });
  spuImageList.value = [];
  spuSaleList.value = [];
  saleIdAndValueName.value = "";
  //储存c3Id
  spuParams.category3Id = c3Id;
  //获取SPU品牌的数据
  let resTrademark = await reqAllTrademark();
  //获取SPU销售属性的数据
  let resAllSale = await reqAllSale();
  //储存数据
  tradeMarkList.value = resTrademark.data;
  allSaleList.value = resAllSale.data;
};

//保存SPU数据
const saveSpuData = async () => {
  spuParams.spuImageList = spuImageList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  // console.log(spuImageList.value);
  spuParams.spuSaleAttrList = spuSaleList.value;
  let result = await reqAddOrUpdateSpu(spuParams);
  // console.log(result);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: spuParams.id ? "修改成功" : "添加成功",
    });
    //通知父亲切换场景为0
    emit("changeScene", {
      sceneNum: 0,
      params: spuParams.id ? "update" : "add",
    });
  } else {
    ElMessage({
      type: "error",
      message: spuParams.id ? "修改失败" : "添加失败",
    });
  }
};
//暴露子组件的方法
defineExpose({ initSpuFormData, initAddSpu });
</script>

<style scoped></style>
